
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>惰性函数与性能</title>
</head>
<body>
    <button id="id">add</button>

    <script>
        var btn = document.getElementById('id')
        function foo (){
            console.log('foo this',this)
        }

        function addEvent (obj, type, fn){
            if(obj.addEventListener){
                obj.addEventListener(type ,fn, false)
            }else if(obj.attachEvent){
                obj.attachEvent(`on${type}`, fn)
            }else{
                obj[`on${type}`] = fn
            }
        }
        
        // 惰性函数
        // 对addEventListener方法重新赋值
        // 在多次调用的场景下，可对后面调用的操作减少判断
        function addEvent (obj, type, fn){
            if(obj.addEventListener){
                addEvent = obj.addEventListener(type ,fn, false)
            }else if(obj.attachEvent){
                addEvent = obj.attachEvent(`on${type}`, fn)
            }else{
                addEvent = obj[`on${type}`] = fn
            }
            return addEvent
        }

        addEvent(btn, 'click', foo)
    </script>
</body>
</html>